<template>
  <BasicModal
    :title="t('layout.header.dropdownItemProfile')"
    v-bind="$attrs"
    @register="registerModal"
    @ok="onButtonOkClick"
    @cancel="onButtonCancelClick"
    width="550px"
    :bodyStyle="{ height: '300px' }"
    :destroy-on-close="true"
  >
    <a-form :labelCol="{ style: 'width:80px' }">
      <a-form-item label="头像">
        <template class="flex">
          <a-upload
            name="avatar"
            list-type="picture-card"
            :maxCount="1"
            accept=".png,.jpg"
            :show-upload-list="false"
            :custom-request="uploadAvatar"
            @remove="removeAvatarFile"
          >
            <!-- <img v-if="userInfo.avatar" :src="getImageFileUrlPrefix + userInfo.avatar" alt="avatar" /> -->
            <div>
              <plus-outlined></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <img v-if="userInfo.avatar" :src="getImageFileUrlPrefix + userInfo.avatar" alt="头像" />
        </template>
      </a-form-item>
      <a-form-item label="签名">
        <div style="margin-bottom: 5px"
          ><a-button type="primary" @click="onOpenEsignModalButtonClick">打开签名板</a-button>
          <a-upload
            :maxCount="1"
            accept=".png,.jpg"
            :show-upload-list="false"
            :custom-request="uploadSign"
            @remove="removeSignFile"
          >
            <a-button class="ml-2">上传签名图片</a-button>
          </a-upload>
          <a-button danger type="text" v-if="userInfo.sign" @click="setSignValue(null)"
            >清空</a-button
          ></div
        >
        <a-image :src="getImageFileUrlPrefix + userInfo.sign" :width="140" v-if="userInfo.sign" />
      </a-form-item>
    </a-form>

    <EsignModal @register="registerSignModal" @success="setSignValue" />
  </BasicModal>
</template>
<script lang="ts">
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { defineComponent, computed, onMounted, h, ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useUserStore } from '/@/store/modules/user';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getImageFileApi, getFileApi } from '/@/api/platform/file';
  import { uploadApi } from '/@/api/platform/upload';
  import { getUserCustomInfo, setUserCustomInfo } from '/@/api/project/user';
  export default defineComponent({
    name: 'ChangePersonInfoModal',
    components: {
      BasicModal,
      BasicForm,
      DeleteOutlined,
      PlusOutlined,
      EsignModal: createAsyncComponent(() => import('/@/views/ehs/Component/EsignModal.vue')),
    },
    emits: ['register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const { t } = useI18n();
      const router = useRouter();
      const { createErrorModal, notification } = useMessage();
      const userStore = useUserStore();
      const { uploadUrl } = useGlobSetting();
      const getImageFileUrlPrefix = ref<string>(uploadUrl + getFileApi);
      const userInfo = ref({
        avatar: '',
        sign: '',
      });

      const [registerSignModal, { openModal: openEsignModal }] = useModal();
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log('打开');
        getUserCustomInfo().then((res) => {
          if (res) {
            userInfo.value = {
              ...userInfo.value,
              ...res,
            };
          } else {
            Object.keys(userInfo.value).forEach((key) => {
              userInfo.value[key] = '';
            });
          }
        });
      });

      async function onButtonOkClick() {
        setUserCustomInfo({
          info: JSON.stringify(userInfo.value),
        })
          .then((res) => {
            if (!res) {
              createMessage.success('保存成功');
              userStore.setUserInfo({
                ...userStore.getUserInfo,
                avatar: userInfo.value.avatar ?? '',
                sign: userInfo.value.sign ?? '',
              });
              onButtonCancelClick();
            } else {
              createMessage.error('保存失败,请稍后重试');
            }
          })
          .catch(() => {
            createMessage.error('保存失败,请稍后重试');
          });
      }

      function onOpenEsignModalButtonClick() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '个人信息维护',
          operateString: '签名',
        };
        openEsignModal(true, propsData);
      }

      function onButtonCancelClick() {
        closeModal();
      }

      function setSignValue(sign) {
        userInfo.value.sign = sign;
      }

      function uploadSign(info) {
        const fileType = info.file.name.split('.').pop();
        // 获取文件类型,如果是excel文件则上传,否则提示文件格式错误
        if (fileType === 'png' || fileType === 'jpg') {
          uploadApi({ system: 'ehs', file: info.file, module: 'attachment' })
            .then((res) => {
              if (res.data.data.success) {
                userInfo.value.sign = res.data.data.fileid;
                createMessage.success('上传成功');
                info.onSuccess(res.data, info);
              } else {
                userInfo.value.sign = undefined;
                createMessage.error('上传失败,请稍后重试');
              }
            })
            .catch((err) => {
              userInfo.value.sign = undefined;
              createMessage.error('上传失败,请稍后重试');
            });
        } else if (fileType !== 'png' && fileType !== 'jpg') {
          userInfo.value.sign = undefined;
          createMessage.error('文件格式不符,请上传图片文件');
        }
      }

      function uploadAvatar(info) {
        const fileType = info.file.name.split('.').pop();
        // 获取文件类型,如果是excel文件则上传,否则提示文件格式错误
        if (fileType === 'png' || fileType === 'jpg') {
          uploadApi({ system: 'ehs', file: info.file, module: 'attachment' })
            .then((res) => {
              if (res.data.data.success) {
                userInfo.value.avatar = res.data.data.fileid;
                createMessage.success('上传成功');
                info.onSuccess(res.data, info);
              } else {
                userInfo.value.avatar = undefined;
                createMessage.error('上传失败,请稍后重试');
              }
            })
            .catch((err) => {
              userInfo.value.avatar = undefined;
              createMessage.error('上传失败,请稍后重试');
            });
        } else if (fileType !== 'png' && fileType !== 'jpg') {
          userInfo.value.avatar = undefined;
          createMessage.error('文件格式不符,请上传图片文件');
        }
      }
      function removeAvatarFile() {
        // 移除上传的文件,清空文件数据
        userInfo.value.avatar = null;
      }
      function removeSignFile() {
        // 移除上传的文件,清空文件数据
        userInfo.value.sign = null;
      }
      onMounted(() => {
        // console.log(userStore.getUserInfo, 'getUserInfo');
      });

      return {
        t,
        h,
        uploadSign,
        uploadAvatar,
        removeAvatarFile,
        removeSignFile,
        userInfo,
        getImageFileUrlPrefix,
        registerModal,
        registerSignModal,
        onButtonOkClick,
        onButtonCancelClick,
        setSignValue,
        onOpenEsignModalButtonClick,
      };
    },
  });
</script>
<style lang="less" scoped>
  img {
    width: 85px;
    height: 85px;
    margin-right: 12px;
    border-radius: 50%;
  }
  .flex {
    display: flex;
    align-items: center;
  }
  .ant-upload-picture-card-wrapper {
    width: 200px;
  }
</style>
